import React, { useState, useEffect, useRef, useCallback } from "react";
import { message } from "antd";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import OrderDetailModal from "@/pages/OrderModule/orderList/components/Actions/common/OrderDetailModal/index.jsx";
import useCommand from "./useCommand";
import useColumns from "./cloumns";
import HeaderTab from "@/components/CommonTab/index";
import LeftBtns from "./component/Actions/LeftBtns";
import ActionsDialog from "./component/Actions/Dialog";
import { getOutboundorderPage, getOutboundorderStatistics, queryStoreList, getErrorReason } from "./service";
import { OUTBOUND_STATUS, CANCELLED } from "@/views/utils/constant";
import { getOrderList } from "@/pages/OrderModule/orderList/services";
import { cloneDeep } from "lodash";
import { useLocation } from "react-router-dom";

const defaultTabArr = () => {
	return [
		{ key: "all", tab: "全部" },
		...OUTBOUND_STATUS.map(item => {
			return {
				tab: item.label,
				key: item.value,
				extra: { num: 0, color: item.value === CANCELLED ? "red" : "" }
			};
		})
	];
};
const defaultType = "all";
const TablePage = () => {
	const [tabArr, setTabArr] = useState(defaultTabArr);
	const [type, setType] = useState(defaultType);
	const RefType = useRef(defaultType);
	const RefErrorList = useRef([]);
	const RefStoreList = useRef([]);

	const [row, setRow] = useState({});
	// 排序相关
	const refOutboundTimeSort = useRef();
	const refOrderCreationTimeSort = useRef();
	const refGoodsCodeSort = useRef();

	const [orderDetailVisible, setOrderDetailVisible] = useState(false);
	const { defaultColumns } = useColumns({
		type,
		setType,
		RefStoreList,
		RefErrorList,
		changeAddress,
		setOrderDetailVisible,
		refOutboundTimeSort,
		refOrderCreationTimeSort,
		refGoodsCodeSort,
		fetchPage,
		handleOpenOrderDetailVisible,
		updateOrderRemarks
	});
	// const [searchData, setSearchData] = useState({});

	const location = useLocation();

	// 接口
	const tableRequest = getOutboundorderPage;
	const [columns, setColumns] = useState(defaultColumns);
	/**
	 * query              搜索json
	 * updateQuery        更新搜索json
	 * fetchList          刷新列表
	 * checkedIds         选中的行id数组
	 * checkedRows        选中的行数据
	 * CheckBoxTable      checkbox多选表格
	 * RadioTable         单选表格
	 */

	// 获取统计数据
	function getStatistics() {
		getOutboundorderStatistics().then(res => {
			const { success, data } = res;
			if (success) {
				const arr = defaultTabArr();
				Object.keys(data).forEach(key => {
					//返回的数据对象的key和字典OUTBOUND_STATUS的value是一致的（有点区别），key清除 - 并且转换成小写对比，
					// {"waitShip": 25,"shipped": 0,"cancelled": 0}
					arr[arr.findIndex(e => e.key.replace("-", "").toLocaleLowerCase() === key.toLocaleLowerCase())].extra.num = data[key];
				});
				setTabArr(arr);
			}
		});
	}
	function resetSourceData(data) {
		return data;
	}
	useEffect(() => {
		getStatistics();
	}, []);
	// 点击重置按钮前执行的方法

	const beforeReset = useCallback(() => {}, []);
	const beforeQuerySearch = ({ API_DATA }) => {
		getStatistics();
		getStoreList();
		getErrorReasonList();
		// 收件人信息相关
		setSearchData(API_DATA, "consigneeKey", "consigneeVal");
		// 备注相关
		setSearchData(API_DATA, "remarkKey", "remarkVal");
		// // 时间类型相关
		// setSearchData(API_DATA, "timeKey", "timeVal");
		const KEYS = ["outboundNo", "systemNo", "shopOrderNo"];
		// 逗号分割转换数组
		KEYS.forEach(key => {
			if (typeof API_DATA[key] === "string") API_DATA[key] = API_DATA[key]?.split(",");
		});
		// 解决调用列表接口Tab状态不一致，不能用type
		API_DATA["outboundStatus"] = RefType.current === "all" ? null : RefType.current;
		// 排序参数
		API_DATA["outboundTimeSort"] = refOutboundTimeSort?.current || null;
		API_DATA["orderCreationTimeSort"] = refOrderCreationTimeSort?.current || null;
		API_DATA["goodsItemOrItems"] = refGoodsCodeSort?.current || null;

		// 标签
		const flagMap = {
			true: 1,
			false: 2
		};
		API_DATA["orderLabelFlag"] = flagMap[API_DATA?.orderLabelIdList?.isLabelOr];
		API_DATA["orderLabelIdList"] = API_DATA?.orderLabelIdList?.containLabelIdArr || null;
		function setSearchData(data, key, value) {
			if (data[key] === undefined) return;
			data[data[key]] = data[value];
			delete data[key];
			delete data[value];
		}
		return API_DATA;
	};

	const { handleCommand, visibleDialogName, customDialogProps, clearDialog } = useCommand({ getFormData });
	// 获取和接口筛选一样的数据
	function getFormData() {
		return getFormValueWithTime(form.getFieldsValue());
	}

	const tableKey = "StockManageOutbound";

	const sortProps = {
		mode: "single",
		onChangeSorts: sortItem => {},

		// 如果只想使用 sort 提供的交互与 UI，但不想让 sort 改变 dataSource，可以设置keepDataSource = true
		keepDataSource: true
	};
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps,
		getFormValueWithTime
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		//
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: true,
		hasQuickSearch: true,
		beforeReset,
		beforeQuerySearch,
		resetSourceData,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true,
		sortProps
	});

	//处理初始化请求
	if (location.state?.orderSn) {
		const orderSn = location.state?.orderSn;
		form.setFieldsValue({
			outboundNo: [orderSn]
		});
		location.state.orderSn = undefined;
	}

	// 查看详情
	async function handleOpenOrderDetailVisible(record) {
		const { data, success } = await getOrderList({ snArr: [record.systemNo] });
		if (success) {
			if (data.records.length === 1) {
				// 有一条数据返回，跳转详情页
				setRow({
					...data.records[0]
				});
				setOrderDetailVisible(true);
			} else {
				message.warning("获取订单信息失败");
			}
		}
	}
	// 修改备注
	function updateOrderRemarks({ record }) {
		handleCommand("修改订单备注", { row: record });
	}

	function changeAddress(ids) {
		form.setFieldsValue({
			consigneeDistrictCode: ids
		});
	}

	function fetchPage() {
		const DATA = form.getFieldValue();
		fetchList(DATA);
	}
	// 当前tab
	const HeaderTabProps = {
		type,
		data: tabArr,
		// tabs 状态变更
		onChange(val) {
			// fetchList();
			setType(val);
			RefType.current = val;
		}
	};
	useEffect(() => {
		RefType.current = type;
		// 需要和tab 状态一致，修改columns 的值
		const list = cloneDeep(columns);
		const index = list.findIndex(e => e.code === "outboundStatus");
		const outboundStatus = type !== "all" ? type : null;
		form.setFieldsValue({ outboundStatus });
		list[index].search.formItemProps.initialValue = outboundStatus;
		setColumns(list);
		const searchData = form.getFieldsValue();
		fetchList({ ...searchData }, { pageNum: 1 });
	}, [type]);

	// 获取店铺
	async function getStoreList() {
		const res = await queryStoreList({
			current: 1,
			size: 9999
		});
		if (res.success) {
			const {
				data: { records }
			} = res;
			RefStoreList.current = records || [];
		}
	}
	//获取异常原因
	async function getErrorReasonList() {
		const { success, data } = await getErrorReason();
		if (success) {
			RefErrorList.current = data || [];
		}
	}

	const leftBtnsProps = {
		type,
		selectedRows,
		handleCommand,
		searchForm: form,
		pagination,
		fetchList
	};

	const actionsDialogProps = {
		orderList: searchSimpleTableProps?.dataSource,
		visibleDialogName,
		type,
		selectedRows,
		customDialogProps,
		handleCommand,
		onCancel: clearDialog,
		searchForm: form,
		fetchList
	};
	return (
		<>
			<SearchCheckboxTable
				key={tableKey}
				header={<HeaderTab {...HeaderTabProps} />}
				leftBtns={<LeftBtns {...leftBtnsProps} />}
				{...searchSimpleTableProps}
			/>
			<ActionsDialog {...actionsDialogProps} />
			{orderDetailVisible && (
				<OrderDetailModal
					item={row}
					orderList={searchSimpleTableProps?.dataSource || []}
					field="systemOrderId"
					handleOk={() => {
						setOrderDetailVisible(false);
						fetchList();
					}}
					onCancel={() => {
						setOrderDetailVisible(false);
					}}
				/>
			)}
		</>
	);
};

export default React.memo(TablePage, () => {
	return true;
});
